package test.com.googlecode.likesql;

import junit.framework.TestCase;

import com.googlecode.likesql.LikeSql;
import com.googlecode.likesql.dml.DML;
import com.googlecode.likesql.expression.AtExp;
import com.googlecode.likesql.expression.QuestExp;

/**
 * @author Johny Huang
 *
 */
public class UpdateSqlTester extends TestCase {

	public void testSimpleSql(){
		String eSql="UPDATE user SET gender='M', name='Tom' WHERE id=123";
		String eTpl="UPDATE user SET gender=?, name=? WHERE id=?";
		
		LikeSql uSql=DML.update("user")
		                .set(QuestExp.qt("gender=?, name=?")
                   		     .set(1, 'M')
                		     .set(2, "Tom"))
		                .where(QuestExp.qt("id=?").set(1,123));
		
		assertEquals(eSql,uSql.toString());
		assertEquals(eTpl,uSql.toTemplate());
	}
	
	public void testAtStyleExpression(){
		String eSql="UPDATE user SET gender='M', name='Tom' WHERE id=123";
		String eTpl="UPDATE user SET gender=?, name=? WHERE id=?";
		
		LikeSql uSql=DML.update("user")
		                .set(AtExp.at("gender=@gender, name=@name")
                   		     .set("gender", 'M')
                		     .set("name", "Tom"))
		                .where(QuestExp.qt("id=?").set(1,123));
		
		assertEquals(eSql,uSql.toString());
		assertEquals(eTpl,uSql.toTemplate());
	}
	
	public void testMultiCriterias(){
		String eSql="UPDATE user SET gender='M', name='Tom' WHERE id=123 and gender='F' or gender='M'";
		String eTpl="UPDATE user SET gender=?, name=? WHERE id=? and gender=? or gender=?";
		
		LikeSql uSql=DML.update("user")
                        .set(QuestExp.qt("gender=?, name=?")
                        		     .set(1, 'M')
                        		     .set(2, "Tom"))
                        .where(QuestExp.qt("id=? and gender=? or gender=?")
                        		  .set(1,123)
                        		  .set(2,"F")
                        		  .set(3,"M"));
		
		assertEquals(eSql,uSql.toString());
		assertEquals(eTpl,uSql.toTemplate());
	}
	
	public void testEmbedSql(){
		String eSql="UPDATE user SET gender='M', name=SELECT name FROM user_backup WHERE id=1 WHERE id=123";
		String eTpl="UPDATE user SET gender=?, name=SELECT name FROM user_backup WHERE id=? WHERE id=?";
		
		LikeSql sSql=DML.select("name").from("user_backup").where(QuestExp.qt("id=?").set(1,1));
		
		LikeSql uSql=DML.update("user")
		                .set(QuestExp.qt("gender=?, name=?")
		                		     .set(1, 'M')
                   		             .set(2, sSql))
		                .where(AtExp.at("id=@id")
		                    	  .set("id",123));
		
		assertEquals(eSql,uSql.toString());
		assertEquals(eTpl,uSql.toTemplate());
	}
	
}
